package com.nervenets.template.service.impl;

import com.nervenets.general.entity.Selection;
import com.nervenets.general.enumeration.Action;
import com.nervenets.general.exception.LogicException;
import com.nervenets.general.service.impl.CacheableServiceImpl;
import com.nervenets.general.web.params.Params;
import com.nervenets.template.hibernate.dao.ManagerDao;
import com.nervenets.template.hibernate.domain.user.Manager;
import com.nervenets.template.hibernate.domain.user.RoleGroup;
import com.nervenets.template.service.ManagerService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ManagerServiceImpl extends CacheableServiceImpl<Manager, ManagerDao> implements ManagerService {
    @Override
    protected void before(Action action, Manager manager, Params... params) {
        if (hasUniqueKey(manager.getId(), "mobile", manager.getMobile())) {
            throw new LogicException(String.format("已存在【%s】账号", manager.getMobile()));
        }
        switch (action) {
            case add:
                break;
            case update:
            case delete:
                checkInit(manager);
                break;
        }
    }

    private void checkInit(Manager manager) {
        Long top1Id = dao.findTop1ManagerIdByOrderById();
        if (null != top1Id && top1Id.equals(manager.getId())) {
            throw new LogicException("为保障安全，初始化管理账号不允许修改，请重新创建账号！");
        }
    }

    @Override
    public Manager findByMobile(String mobile) {
        return dao.findByMobile(mobile);
    }

    @Override
    public long countByRoleGroupsId(RoleGroup roleGroup) {
        return dao.countByRoleGroupsIdAndDeleted(roleGroup.getId(), 0);
    }

    @Override
    public List<Manager> findAllByRoleGroup(RoleGroup roleGroup) {
        return dao.findAllByRoleGroupsIdAndDeleted(roleGroup.getId(), 0);
    }

    @Override
    public List<Selection> selections() {
        return findAll("id", "name").stream().map(map -> new Selection(map.get("name").toString(), String.valueOf(map.get("id")))).collect(Collectors.toList());
    }
}
